package com.geqian.web.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author geqian
 * @date 13:44 2023/11/18
 */
public class TemplateUtils {
    /**
     * 文件模板
     *
     * @throws Exception
     */
    public static void fillTemplate(Map<String, Object> params, String templatePath, String outputPath) throws Exception {

        try (FileOutputStream file = new FileOutputStream(outputPath);
             OutputStreamWriter out = new OutputStreamWriter(file, StandardCharsets.UTF_8)
        ) {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_21);

            //设置字符集
            configuration.setDefaultEncoding("utf-8");

            // 设置模板路径
            configuration.setDirectoryForTemplateLoading(new File(templatePath.substring(0, templatePath.lastIndexOf(File.separator))));

            //获取模板
            Template template = configuration.getTemplate(templatePath.substring(templatePath.lastIndexOf(File.separator) + 1));

            template.process(params, out);

            out.flush();
        }
    }
}
